## Viasat provide an API to fetch images for the programmes in their TV Guide

module Shin
  module Data
    class Viasat
      
      def new
        self
      end
      
      # 
      def images(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get('http://se.press.viasat.tv/export?id=' + params[:id].to_s + '&enhancedinfo=true')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Its splitted by newlines
        data = response.body.split( /\r?\n/ ) rescue nil
        
        # Just check to be sure
        if data != nil and data != "" and data.kind_of?(Array)
          # For each do this
          array = {portrait: nil, landscape: nil, all: []}
          
          data.each do |d|
            url, width, height, image_type, removed = d.split(",")
            # Just return one
            if image_type == 'portrait' and array[:portrait] == nil
              array[:portrait] = url
            elsif image_type == 'landscape' and array[:landscape] == nil
              array[:landscape] = url
            else
              # We don't add the ones already specified above.
              array[:all] << {url: url, width: width, height: height, type: image_type}
            end
          end
          
          array.to_hashugar
        else
          raise NotValid, "We failed to parse the document."
        end
        
      end
      
      # Error
      class NotValid         < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end